#include "events_cb.hpp"
#include "worker_thread.hpp"
#include "thread_task.hpp"
#include "task_factory.hpp"
#include "thread_pool.hpp"
#include "task_data.hpp"
#include "task_server_cmd.hpp"

#include <thread>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <glog/logging.h>
events_cb::events_cb(/* args */)
{
}

events_cb::~events_cb()
{
}
void events_cb::event_cb(struct evconnlistener * e, evutil_socket_t fd, sockaddr *addr, int socklen, void *arg)
{
    thread_task* task = task_factory::getInstance()->create_task();
    task->m_sockfd = fd;
    thread_pool::getInstance()->dispatch(task);   
}
void events_cb::event_worker_cb(evutil_socket_t fd, short what, void *arg)
{
    VLOG(0)<<"signal thread";
    worker_thread *th = reinterpret_cast<worker_thread*>(arg);
    th->notify(fd,what);
    
}
void events_cb::event_read_cb(struct bufferevent *bev, void *ctx)
{
    task_server_cmd* cmd = reinterpret_cast<task_server_cmd*>(ctx);

    char recv_msg[1024] = {0};
    VLOG(0)<<"events_cb";
    for(;;)
    {
        int len = bufferevent_read(bev,recv_msg,sizeof(recv_msg)-1);
        if(len <= 0)
            break;
        std::string type = "";
        for (size_t i = 0; i < len; ++i)
        {
            if(recv_msg[i]== ' '||recv_msg[i]=='\r')
            break;
            type +=recv_msg[i];
        }
        // 获取消息类型
        int count = 0;

        if(cmd->m_call_task.find(type) != cmd->m_call_task.end())
        {
            task_data* t = cmd->m_call_task[type];
            t->m_base = cmd->m_base;
            t->m_cmd_task = cmd;
            t->parse_cmd(type,recv_msg);
        }
    }
}